﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kstopa.Sqlsugar.Serivices.System.Org
{
    public class SysOrgService : SqlSugarRepository<SysOrg>, ISysOrgService

    {
        private readonly ISimpleCacheService _simpleCacheService;

        public SysOrgService(ISugarDbContextProvider<ISqlSugarDbContext> sugarDbContextProvider,
            ISimpleCacheService simpleCacheService
            ) : base(sugarDbContextProvider)
        {
            _simpleCacheService = simpleCacheService;
        }


        public async Task<List<long>> GetOrgChildIds(long orgId, bool isContainOneself = true)
        {
            var orgIds = new List<long>();//组织列表
            if (orgId > 0)//如果orgid有值
            {
                //获取所有子集
                var sysOrgs = await GetChildListById(orgId, isContainOneself);
                orgIds = sysOrgs.Select(x => x.Id).ToList();//提取ID列表
            }
            return orgIds;
        }
        /// <inheritdoc />
        public async Task<List<SysOrg>> GetChildListById(long orgId, bool isContainOneself = true)
        {
            //获取所有组织
            var sysOrgs = await GetListAsync();
            //查找下级
            var childLsit = GetSysOrgChilden(sysOrgs, orgId);
            if (isContainOneself)//如果包含自己
            {
                //获取自己的组织信息
                var self = sysOrgs.Where(it => it.Id == orgId).FirstOrDefault();
                if (self != null) childLsit.Insert(0, self);//如果组织不为空就插到第一个
            }
            return childLsit;
        }
        /// <summary>
        /// 获取组织所有下级
        /// </summary>
        /// <param name="orgList"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public List<SysOrg> GetSysOrgChilden(List<SysOrg> orgList, long parentId)
        {
            //找下级组织ID列表
            var orgs = orgList.Where(it => it.ParentId == parentId).ToList();
            if (orgs.Count > 0)//如果数量大于0
            {
                var data = new List<SysOrg>();
                foreach (var item in orgs)//遍历组织
                {
                    var childen = GetSysOrgChilden(orgList, item.Id);//获取子节点
                    data.AddRange(childen);//添加子节点);
                    data.Add(item);//添加到列表
                }
                return data;//返回结果
            }
            return new List<SysOrg>();
        }

    }
}
